package com.lechi.iot.netty.utils;

import com.lechi.web.common.exception.ServiceException;

import java.io.ByteArrayOutputStream;

/**
 * Utility class for converting hex data to bytes and back again.
 */
public class Hex {
    private static final HexEncoder encoder = new HexEncoder();

    public static String toHexString(
            byte[] data) {
        return toHexString(data, 0, data.length);
    }

    public static String toHexString(
            byte[] data,
            int off,
            int length) {
        byte[] encoded = encode(data, off, length);
        return fromByteArray(encoded);
    }

    public static byte[] encode(
            byte[] data,
            int off,
            int length) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        try {
            encoder.encode(data, off, length, bOut);
        } catch (Exception e) {
            throw new ServiceException("exception encoding Hex string: " + e.getMessage());
        }

        return bOut.toByteArray();
    }

    public static String fromByteArray(byte[] bytes) {
        return new String(asCharArray(bytes));
    }


    public static char[] asCharArray(byte[] bytes) {
        char[] chars = new char[bytes.length];

        for (int i = 0; i != chars.length; i++) {
            chars[i] = (char) (bytes[i] & 0xff);
        }

        return chars;
    }

}
